#include "monoSampleSlopeColumn.h"

#define JITTER_RIGHT 0.5

/** 
  * unfortunately this projection is not entirely correct:
  * a vertical line in screen space is not in general vertical in world space
  * however, this cannot be solved without a (slower) multisampling algorithm
  */
void monoSampleSlopeColumn(Scene& scene, Viewerf& viewer) {
    Vector3f& pos = viewer.pos;
    Vector3f& frontDir = viewer.dir;
    Vector3f rightDir = frontDir ^ Vector3f(0, 0, 1);
    Vector3f upDir = rightDir ^ frontDir;

    float scale = tan(viewer.fov * 0.5);

    Color3f* colors = new Color3f[viewer.viewsizeY];
    float* dirZ = new float[viewer.viewsizeY];

    for (int j = 0; j < viewer.viewsizeY; j++) {
        float up = float(j) / viewer.viewsizeY - 0.5;
        Vector3f dir = frontDir + up * scale * upDir;
        dirZ[j] = dir.getSlope();
    }

    glBegin(GL_POINTS);
        for (int i = 0; i < viewer.viewsizeX; i++) {
            float right = (float(i) + JITTER_RIGHT * (randf() - 0.5)) / viewer.viewsizeX - 0.5;
            Vector3f columnDir = frontDir + right * scale * rightDir;

            columnDir.normalize2d();
            SlopeRayColumn slopeRayColumn(pos, columnDir.x, columnDir.y, dirZ, viewer.viewsizeY);
            scene.traceSlopeRayColumn(colors, slopeRayColumn);

            for (int j = 0 ; j < viewer.viewsizeY; j++) {
                setPixel(i, j, colors[j]);
            }
        }
    glEnd();

    delete[] dirZ;
    delete[] colors;
}
